import java.util.concurrent.Semaphore;

/**
 * @author gao
 * @date 2025/8/4 23:44
 */

public class Demo4 {
    private static int count = 0;
    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);

        // 创建一个线程t1，该线程执行的任务是：循环50_000次，每次执行时获取semaphore的许可，然后count加1，最后释放semaphore的许可
        Thread t1 = new Thread(() ->{
            for (int i = 0; i < 50_000; i++) {
                try {
                    //  获取semaphore的许可
                    semaphore.acquire();
                    // count加1
                    count++;
                    // 释放semaphore的许可
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread t2 = new Thread(() ->{
            for (int i = 0; i < 50_000; i++) {
                try {
                    semaphore.acquire();
                    count++;
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(count);
    }
}